﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KgUtils.Web
{
    public static partial class PageExtension
    {
        /// <summary>
        /// Get the control that provoked the current postback
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static Control GetPostBackControl(this Page page)
        {
            Control control = null;

            string ctrlname = page.Request.Params.Get("__EVENTTARGET");
            if (!ctrlname.IsNullOrEmpty())
            {
                control = page.FindControl(ctrlname);
            }
            else
            {
                foreach (string ctl in page.Request.Form)
                {
                    if (!ctl.IsNullOrEmpty())
                    {
                        Control c = page.FindControl(ctl);
                        if (c is System.Web.UI.WebControls.Button)
                        {
                            control = c;
                            break;
                        }
                    }
                }
            }
            return control;
        }

        public static bool ValidateTextBoxMaxLength(this Page page, ControlCollection controls)
        {
            foreach (Control ctrl in controls)
            {
                if (ctrl.Controls != null)
                {
                    if (!page.ValidateTextBoxMaxLength(ctrl.Controls))
                        return false;
                }
                if (ctrl is TextBox)
                {
                    var txt = (TextBox)ctrl;
                    if (txt.Text != null && txt.MaxLength != 0 && txt.MaxLength < txt.Text.Length)
                        return false;
                }
            }

            return true;
        }
    }
}
